<template>
  <el-dialog
    title="提示"
    :visible.sync="dialogVisible"
    :before-close="handleClose"
  >
    <div>
      <span>用户名：</span>
      <el-input v-model="searchParams.username" />
    </div>
    <div>
      <span>密码：</span>
      <el-input v-model="searchParams.password" />
    </div>
    <div>
      <span>邮箱：</span>
      <el-input v-model="searchParams.email" />
    </div>
    <div>
      <span>手机号：</span>
      <el-input v-model="searchParams.mobile" />
    </div>
    <div>
      <span>头像：</span>
      <el-upload
        class="avatar-uploader"
        :action="`${bast_url}/xxl/file/upload`"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :headers="headers"
      >
        <img
          v-if="searchParams.avatar"
          :src="searchParams.avatar"
          class="avatar"
        />
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </div>
    <div>
      <span>状态：</span>
      <el-input v-model="searchParams.status" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="comfire">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import Cookies from "js-cookie";
import { addUser } from "@/api/xxl-springboot/user.js";
const bast_url = window.SITE_CONFIG["apiURL"];
export default {
  props: {
    status: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      bast_url,
      headers: {
        token: Cookies.get("token"),
      },
      searchParams: {
        username: "",
        password: "",
        email: "",
        mobile: "",
        avatar: "",
        status: 1,
      },
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.status;
      },
      set(val) {
        this.$emit("update:status", val);
      },
    },
  },
  methods: {
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.searchParams.avatar = res.data.url;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    async comfire() {
      const { code } = await addUser(this.searchParams);
      if (code == 200) {
        this.$emit("update:status", false);
        this.$emit("ok");
      }
    },
    /**
     * 点击右上角的关闭按钮
     * @param {*} done 函数控制是否关闭
     */
    handleClose(done) {
      done();
    },
  },
};
</script>
